package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.EntryDB;
import worklog.dto.EntryDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/saveDay")
public class SaveDay extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private EntryDB entryDB;
	private int rowsPerDay = 8;
	private ResponseDTO responder = new ResponseDTO();

    public SaveDay() { super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		entryDB = new EntryDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	out.print(processRequest(request));
    	entryDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

		int paramLength = request.getParameterMap().size(), res = -1;
        
    	if (paramLength > 0) {
    		String date = request.getParameter("date"), desc, sId;
    		int id;
    		
    		EntryDTO[] entries = new EntryDTO[rowsPerDay];
    		EntryDTO entry;
    		for (int i = 0; i < rowsPerDay; i++){
    			desc = request.getParameter("rows["+i+"][description]");
    			sId = request.getParameter("rows["+i+"][projectId]");
    			if (sId != null && !sId.isEmpty()) id = Integer.parseInt(sId); 
    			else id = 0;
    			
	    		entry = new EntryDTO();
	    		entry.setDay(date);
	    		entry.setUserId(userId);
	    		entry.setType(i+1);
	    		entry.setProjectId(id);
	    		entry.setDescription(desc);
	    		entries[i] = entry;
    		}
			
			res = entryDB.saveDay(entries, userId);
    		
			if (res == -1) return responder.showError("DB error");
			else return responder.showSuccess();
    	}	
		return responder.showError();
	}
}
